package com.module.my.set.model

import android.content.Context
import android.text.InputType
import android.text.TextUtils
import com.module.app.base.BaseViewModel
import com.module.app.bean.ConfigBean
import com.module.app.bean.IType
import com.module.base.cache.CacheSDK
import com.module.base.ext.request
import com.module.app.utils.EncodeNameUtils
import com.module.base.utils.ToastUtils
import com.module.app.widget.keyboard.InputBuilder.OnMyClickListener
import com.module.app.widget.keyboard.InputConfirmDialog
import com.module.frame.ext.postEvent
import com.module.my.R
import com.module.third.learcloud.lcSave
import kotlinx.coroutines.flow.MutableSharedFlow

class SetPasswordModel : BaseViewModel() {

    var context: Context? = null

    /**
     *  双重校验锁式-单例   列表
     */
    val commonPasswordFlow: MutableSharedFlow<Boolean> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    fun onClickCommonPassword() {
        val dialog: com.module.app.widget.keyboard.InputConfirmDialog = com.module.app.widget.keyboard.InputConfirmDialog.Builder(context)
            .setTitle("设置通用密码")
            .setMaxLength(4)
            .setInputType(InputType.TYPE_CLASS_NUMBER)
            .setConfirmButton(R.string.confirm)
            .setCancelButton(R.string.cancel)
            .setOnConfirmListener(object : OnMyClickListener() {
                override fun onClick(dialog: com.module.app.widget.keyboard.InputConfirmDialog, text: String) {
                    setCommonPassword(text)
                    dialog.hide()
                }
            }).create()
        dialog.show()
    }

    private fun setCommonPassword(password: String) {
        request({
            val configBean = com.module.app.bean.ConfigBean.getInstance()
            if (TextUtils.isEmpty(password) || password.length < 4) {
                configBean.password = ""
            } else {
                configBean.password = com.module.app.utils.EncodeNameUtils.encode(password)
            }
            lcSave(configBean, configBean.objectId, com.module.app.bean.ConfigBean::class.java)
        }, {
            if (it != null) {
                CacheSDK.put(com.module.app.bean.IType.ICache.CONFIG, it)
            }
            ToastUtils.showShort("设置成功")
            postEvent(commonPasswordFlow, true)
        }, {
            ToastUtils.showShort(it.msg)
        })
    }

}